package com.dems.admin.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dems.admin.security.SecurityUtils;
import com.dems.dao.dataobject.User;
import com.dems.domain.JsonResponse;
import com.dems.domain.ModifyPasswordReqVO;
import com.dems.domain.UserReqVO;
import com.dems.domain.UserVO;
import com.dems.domain.constant.DianConstant;
import com.dems.domain.enumerate.UserTypeEnum;
import com.dems.domain.org.DeptStaffDto;
import com.dems.domain.user.UserBasicMessageVO;
import com.dems.domain.user.UserHomeDto;
import com.dems.service.impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 用户相关接口
 */
@RefreshScope
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Value("${la.h5.url}")
    private String H5_URL;

    @Value("${la.config.defaultPwd}")
    private String defaultPwd;
    @Value("${la.config.partnerId:0}")
    private Long LA_CONFIG_PARTNERID;

    @PostMapping("/fetchUserInfo")
    public JsonResponse<JSONObject> fetchUserInfo() {
        JSONObject userResVO = new JSONObject();
        User loanassistUser = SecurityUtils.getLoanassistUser();
        User dbloanassistUser = this.userService.fetchUser(loanassistUser.getUserId());
        if (dbloanassistUser != null) {
            loanassistUser = dbloanassistUser;
        }
        userResVO.put("phoneNo", loanassistUser.getPhoneNo());
        userResVO.put("nickname", loanassistUser.getNickname());
        userResVO.put("headimgUrl", loanassistUser.getHeadimgUrl());
        userResVO.put("userType", loanassistUser.getUserType());
        userResVO.put("openId", loanassistUser.getOpenId());
        userResVO.put("userId", loanassistUser.getUserId());
        userResVO.put("name", loanassistUser.getName());
        userResVO.put("inviteUrl", H5_URL + DianConstant.INVITE_URL_PREFIX + loanassistUser.getPartnerCode());
        userResVO.put("email", loanassistUser.getEmail());
        userResVO.put("workCity", loanassistUser.getWorkCity());
        userResVO.put("country", loanassistUser.getCountry());
        userResVO.put("province", loanassistUser.getProvince());
        userResVO.put("companyName", loanassistUser.getCompanyName());
        userResVO.put("companyId", loanassistUser.getCompanyId());
        userResVO.put("buId", (loanassistUser.getBuId() != null && loanassistUser.getBuId() != 0)
                ? loanassistUser.getBuId() : LA_CONFIG_PARTNERID.intValue());
        userResVO.put("personIntroduction", loanassistUser.getPersonIntroduction());
        userResVO.put("creditAccount", loanassistUser.getCreditAccount());
        loanassistUser = userService.fetchUser(loanassistUser.getUserId());

        String profile = loanassistUser.getProfile();
        if (StringUtils.isNotBlank(profile)) {
            JSONObject profileJson = JSONObject.parseObject(profile);
            userResVO.put("sipAccount", profileJson.getString("sipAccount"));
            userResVO.put("sipPassword", profileJson.getString("sipPassword"));
            if(profileJson.get("number") != null) {
                userResVO.put("number", profileJson.getString("number"));
            }
        }

        if (UserTypeEnum.checkTypeRole(loanassistUser.getUserType(), loanassistUser.getRoleCodeList(), UserTypeEnum.L1, UserTypeEnum.VL, UserTypeEnum.BIZ_VISIT_L, UserTypeEnum.T, UserTypeEnum.M)) {
            userResVO.put("parterUrl", H5_URL + DianConstant.PARTER_URL_PREFIX + loanassistUser.getPartnerCode());
        }


        if (loanassistUser != null) {
            userResVO.put("roleCodeList", loanassistUser.getRoleCodeList());
            userResVO.put("menuCodeList", loanassistUser.getMenuCodeList());
        }

        return new JsonResponse<>(userResVO);
    }

    @PostMapping("/modifyPwd")
    public JsonResponse modifyPwd(@RequestBody @Valid ModifyPasswordReqVO modifyPasswordReqVO) {

        User user = SecurityUtils.getLoanassistUser();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        // 密码匹配
        if (!encoder.matches(modifyPasswordReqVO.getLastPassword(), user.getPassword())) {
            JsonResponse res = JsonResponse.fail();
            res.setMessage("旧密码不匹配");
            return res;
        }

        modifyPasswordReqVO.setNewPassword(encoder.encode(modifyPasswordReqVO.getNewPassword()));

        userService.modifyPwd(user, modifyPasswordReqVO);


        return JsonResponse.success();
    }

    /**
     * 渠道商户列表
     */
    @PostMapping("/partnerList")
    public JsonResponse partnerList(@RequestBody UserReqVO userReqVO) throws InvocationTargetException, IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        Page<UserVO> data = userService.fetchUserList(user, userReqVO);
        return new JsonResponse<>(data);
    }

    /**
     * 渠道商户列表
     */
    @PostMapping("/partnerListV2")
    public JsonResponse<Page<DeptStaffDto>> partnerListV2(@RequestBody UserReqVO userReqVO) throws InvocationTargetException,
            IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        Page<DeptStaffDto> data = userService.fetchUserListV2(user, userReqVO);
        return new JsonResponse<>(data);
    }

    @PostMapping("/downLoadPartnerListV2")
    public JsonResponse downLoadPartnerListV2(@RequestBody UserReqVO userReqVO) throws InvocationTargetException, IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        userService.downLoadPartnerListV2(user, userReqVO);
        return JsonResponse.success();
    }
    /**
     * 渠道商户列表
     */
    @PostMapping("/modifyUserType")
    public JsonResponse modifyUserType(@RequestBody UserReqVO userReqVO) throws InvocationTargetException, IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        User data = userService.modifyUserType(user, userReqVO);
        return new JsonResponse<>(data);
    }
    /**
     * 离职
     */
    @PostMapping("/fireUser")
    public JsonResponse fireUser(@RequestBody UserReqVO userReqVO) throws InvocationTargetException, IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        User data = userService.fireUser(user, userReqVO);
        return new JsonResponse<>(data);
    }
    /**
     * 注销账户，完全失效当前用户，重新注册的话，是生成新账户
     */
    @PostMapping("/deactivateUser")
    public JsonResponse deactivateUser(@RequestBody UserReqVO userReqVO) throws InvocationTargetException, IllegalAccessException {
        User user = SecurityUtils.getLoanassistUser();
        User data = userService.deactivateUser(user, userReqVO);
        return new JsonResponse<>(data);
    }


    @PostMapping("/allocateUserList")
    public JsonResponse<List<UserVO>> allocateUserList(@RequestBody UserReqVO userReqVO) {
        return JsonResponse.success(userService.fetchAllocateUserList(userReqVO, SecurityUtils.getLoanassistUser()));
    }

    @PostMapping("/saveSipInfo")
    public JsonResponse<Integer> saveSipInfo(@RequestBody UserReqVO userReqVO) {
        return JsonResponse.success(userService.saveSipInfo(userReqVO, SecurityUtils.getLoanassistUser()));
    }

    @PostMapping("/sendUserInfo")
    public JsonResponse<JSONObject> sendUserInfo(@RequestBody UserReqVO userReqVO) {
        return JsonResponse.success(userService.sendUserInfo(userReqVO, SecurityUtils.getLoanassistUser()));
    }

    @PostMapping("/add")
    public JsonResponse<User> addUser(@RequestBody UserReqVO userReqVO) {
        return JsonResponse.success(userService.addUser(userReqVO, SecurityUtils.getLoanassistUser()));
    }

    /**
     * 修改用户头像
     * */
    @PostMapping("/updateBasicMessage")
    public JsonResponse<String> updateBasicMessage(@RequestBody UserBasicMessageVO userBasicMessageVO){
        return JsonResponse.success(this.userService.updateBasicMessage(userBasicMessageVO));
    }

    /**
     * 清空用户Sip信息
     * */
    @PostMapping("/clearSipInfo")
    public JsonResponse<Integer> clearSipInfo(@RequestBody UserReqVO userReqVO) {
        return JsonResponse.success(this.userService.clearSipInfo(userReqVO));
    }

    /**
     * 重置密码接口
     * 默认密码为：1234
     * */
    @PostMapping("/resetPwd")
    public JsonResponse resetPwd(@RequestBody ModifyPasswordReqVO modifyPasswordReqVO) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(modifyPasswordReqVO.getNewPassword() == null){
            modifyPasswordReqVO.setNewPassword(this.defaultPwd);
        }
        modifyPasswordReqVO.setNewPassword(encoder.encode(modifyPasswordReqVO.getNewPassword()));
        User user = new User();
        user.setOpenId(modifyPasswordReqVO.getUserId());
        this.userService.resetPwd(modifyPasswordReqVO);
        return JsonResponse.success();
    }

    /**
     * 重置密码接口
     * 默认密码为：1234
     * */
    @PostMapping("/changeStatus")
    public JsonResponse changeWorkStatus(@RequestBody ModifyPasswordReqVO modifyPasswordReqVO) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(modifyPasswordReqVO.getNewPassword() == null){
            modifyPasswordReqVO.setNewPassword(this.defaultPwd);
        }
        modifyPasswordReqVO.setNewPassword(encoder.encode(modifyPasswordReqVO.getNewPassword()));
        User user = new User();
        user.setOpenId(modifyPasswordReqVO.getUserId());
        this.userService.resetPwd(modifyPasswordReqVO);
        return JsonResponse.success();
    }
    @PostMapping("/update")
    public JsonResponse updateUser(@RequestBody UserReqVO userReqVO){
        User user = SecurityUtils.getLoanassistUser();
        return JsonResponse.success(this.userService.updateUser(user, userReqVO));
    }

    @PostMapping("/fetchUserInfoById")
    public JsonResponse findUserById(@RequestBody UserReqVO userReqVO){
        return new JsonResponse<>(this.userService.findUserById(userReqVO));
    }
}
